﻿using System;
using System.ComponentModel;

namespace PocketBook.Model
{
    public abstract class CustomisableDesign<T> : Design, IEditableObject where T : class, ICloneable, new()
    {
        private T _originalSettings;

        protected CustomisableDesign() : this(new T())
        {
        }

        protected CustomisableDesign(CustomisableDesign<T> design) : this(design.ClonedSettings)
        {
        }

        private CustomisableDesign(T settings)
        {
            Settings = settings;
            IsCustomisable = true;
        }

        public T Settings { get; private set; }

        #region IEditableObject

        void IEditableObject.BeginEdit()
        {
            if (_originalSettings != null) return;

            _originalSettings = ClonedSettings;
        }

        void IEditableObject.CancelEdit()
        {
            if (_originalSettings == null) return;

            Settings = _originalSettings;
            _originalSettings = null;
            
            Refresh();
        }

        void IEditableObject.EndEdit()
        {
            _originalSettings = null;
        }

        #endregion

        public override object Clone()
        {
            var design = (CustomisableDesign<T>) base.Clone();
            design.Settings = ClonedSettings;

            return design;
        }

        private T ClonedSettings
        {
            get { return (T) Settings.Clone();  }
        }

    }
}